{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "vh24NWimaXtR"
   },
   "source": [
    "# Chapter 3 - Methods and Functions：方法與函式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JEdL9FX4AmLt"
   },
   "source": [
    "## 指定變數 Variable（= 物件 Object）表達式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "34eVaBh-cju2"
   },
   "source": [
    "如同代數一樣，在撰寫程式時，我們也可以像代數一樣，用某個代號來稱呼某些內容。\n",
    "\n",
    "一般的程式都稱這種代換的內容為變數 (Variable）。在 Python 中，所有可以操作的內容都是繼承「物件 (`object`)」類別而衍生的，所以變數也等同於物件。\n",
    "\n",
    "指定物件時，會將等號右側的內容指定給左側的物件，例如 `n = 10`，即是將整數 `10` 指定給物件 `n`。\n",
    "\n",
    "> 備註：跟一般的數學式子不一樣，在程式語言中，一個等號 `=` 是代表「指定」，兩個等號 `==` 才是比較左右兩側的內容是否一致。\n",
    "\n",
    "References:\n",
    "\n",
    "* [Simple statements - Python Documentation](https://docs.python.org/3/reference/simple_stmts.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 956,
     "status": "ok",
     "timestamp": 1606899231685,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "idvh2H1mAxPC",
    "outputId": "2c8a9669-c709-4620-85b6-f3bbc3fadfa5"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello world!\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "source": [
    "# 範例：建立一個字串物件\n",
    "s = \"Hello world!\"\n",
    "print(s)\n",
    "print(type(s))  # 驗證此物件是否為 str 型態"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "OkdTUuECN_9i"
   },
   "source": [
    "而物件的名稱需要參照命名規則。一般來說，要注意的事項如下：\n",
    "\n",
    "* 名稱不以數字開頭\n",
    "* 名稱中不包含 `-`（會與減法運算子混淆）\n",
    "* 名稱需避開 Python Keywords（參見[官方文件中的內容](https://docs.python.org/3/reference/lexical_analysis.html#keywords)）\n",
    "\n",
    "另外，Google Python Style Guide 另有列出一串建議的命名方式：\n",
    "\n",
    "```\n",
    "module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name.\n",
    "```\n",
    "\n",
    "References:\n",
    "\n",
    "* [Keywords - Python Documentation](https://docs.python.org/3/reference/lexical_analysis.html#keywords)\n",
    "* [Naming Conventions](https://www.python.org/dev/peps/pep-0008/#naming-conventions)\n",
    "* [Namings - Gogole Python Stule Guide](https://google.github.io/styleguide/pyguide.html#s3.16-naming)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 4287,
     "status": "ok",
     "timestamp": 1606900790857,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "TTiCXpHRA2WI",
    "outputId": "a9215883-6c14-4d72-ea4c-751db3ed22ed"
   },
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "Hi, what's your name?  Vivi\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "So you are Vivi. Welcome!\n"
     ]
    }
   ],
   "source": [
    "# 搭配內建函式 input()，可以在執行時出現一個輸入窗格，讓使用者輸入內容並記錄起來\n",
    "input_str = input(\"Hi, what's your name? \")\n",
    "print(\"So you are\", input_str + \".\", \"Welcome!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "E0vIO2gLT8Jy"
   },
   "source": [
    "### Augmented assignment statements：增強賦值陳述式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "nTgjsrBJhhfc"
   },
   "source": [
    "增強賦值陳樹是的用途，就是將運算子與指定變數的語句合而為一。例如 `+=` 會將等號右側的內容與左側相加之後，再指定給等號左側的物件。\n",
    "\n",
    "References:\n",
    "\n",
    "* [Augmented assignment statements](https://docs.python.org/3/reference/simple_stmts.html?highlight=additional%20assignment#augmented-assignment-statements)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "number = 1\n",
    "number += 2\n",
    "# number = number + 2  # 此表達式與上式等價\n",
    "print(number)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "OWmkOr8Ynwp3"
   },
   "source": [
    "## 複習: 使用物件的方法 (methods)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "fB_RCKeNikGU"
   },
   "source": [
    "物件本身不只是可以用來儲存內容，很多物件都會內建一些好用的方法讓我們調用。在上一個章節，我們嘗試調用了字串物件的方法，這裡先回顧一下呼叫方法的方式：執行 `object.method()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "eoihpvKJn4tv"
   },
   "source": [
    "### 字串方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1042,
     "status": "ok",
     "timestamp": 1606899252001,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "iaPIPogAn7_0",
    "outputId": "0a4db039-8bde-46a6-ab7c-ad59921ef876"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "HELLO WORLD!\n",
      "hello world!\n",
      "Hello World!\n"
     ]
    }
   ],
   "source": [
    "s = \"Hello world!\"\n",
    "print(s.upper())  # 將字串轉換為大寫\n",
    "print(s.lower())  # 將字串轉換為小寫\n",
    "print(s.title())  # 將字串中的每個字詞的首字元轉換為大寫"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "xi8Xz4_7jMfm"
   },
   "source": [
    "## 常用的內建函式 (functions)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "tDAmAmhSeHZ8"
   },
   "source": [
    "與方法相似的物件為函式 (functions）。與方法不同的是，呼叫函式時，不需要建立物件，直接呼叫函式即可：執行 `function()`\n",
    "\n",
    "接下來我們會以一些常用的內建函式作為範例。\n",
    "\n",
    "References:\n",
    "\n",
    "* [Built-in Functions - Python Documentation](https://docs.python.org/3/library/functions.html)\n",
    "* [Glossary - Python Documentation](https://docs.python.org/3/glossary.html)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "oOqnPexol2lv"
   },
   "source": [
    "### `help()`: 取得某物件的使用說明"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1288,
     "status": "ok",
     "timestamp": 1607417931451,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "DZvkAsSDaRia",
    "outputId": "d278b295-0047-481c-8078-610f84926cf3"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function print in module builtins:\n",
      "\n",
      "print(...)\n",
      "    print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n",
      "    \n",
      "    Prints the values to a stream, or to sys.stdout by default.\n",
      "    Optional keyword arguments:\n",
      "    file:  a file-like object (stream); defaults to the current sys.stdout.\n",
      "    sep:   string inserted between values, default a space.\n",
      "    end:   string appended after the last value, default a newline.\n",
      "    flush: whether to forcibly flush the stream.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(print)  # 取得 print() 函式的使用說明"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "lHyd2NoIl8Ze"
   },
   "source": [
    "### `type()`: 取得指定物件的物件型態"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "id": "VeTQSiIElqNy"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'str'>\n"
     ]
    }
   ],
   "source": [
    "print(type(\"Hello world!\"))  # 取得 \"Hello world!\" 物件的物件型態"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Tm6eciGpl6Dq"
   },
   "source": [
    "### `dir()`: 取得指定物件的屬性 (attributes) 及方法 (methods)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "-8kexjculCED"
   },
   "source": [
    "> 備註：至於什麼是「屬性」？我們會在類別的章節再次講解。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1033,
     "status": "ok",
     "timestamp": 1606898341677,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "qIoIFASjlSjC",
    "outputId": "8d0307e6-3bf3-48e0-98ee-8aa66aea9301"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['__add__',\n",
       " '__class__',\n",
       " '__contains__',\n",
       " '__delattr__',\n",
       " '__dir__',\n",
       " '__doc__',\n",
       " '__eq__',\n",
       " '__format__',\n",
       " '__ge__',\n",
       " '__getattribute__',\n",
       " '__getitem__',\n",
       " '__getnewargs__',\n",
       " '__gt__',\n",
       " '__hash__',\n",
       " '__init__',\n",
       " '__init_subclass__',\n",
       " '__iter__',\n",
       " '__le__',\n",
       " '__len__',\n",
       " '__lt__',\n",
       " '__mod__',\n",
       " '__mul__',\n",
       " '__ne__',\n",
       " '__new__',\n",
       " '__reduce__',\n",
       " '__reduce_ex__',\n",
       " '__repr__',\n",
       " '__rmod__',\n",
       " '__rmul__',\n",
       " '__setattr__',\n",
       " '__sizeof__',\n",
       " '__str__',\n",
       " '__subclasshook__',\n",
       " 'capitalize',\n",
       " 'casefold',\n",
       " 'center',\n",
       " 'count',\n",
       " 'encode',\n",
       " 'endswith',\n",
       " 'expandtabs',\n",
       " 'find',\n",
       " 'format',\n",
       " 'format_map',\n",
       " 'index',\n",
       " 'isalnum',\n",
       " 'isalpha',\n",
       " 'isdecimal',\n",
       " 'isdigit',\n",
       " 'isidentifier',\n",
       " 'islower',\n",
       " 'isnumeric',\n",
       " 'isprintable',\n",
       " 'isspace',\n",
       " 'istitle',\n",
       " 'isupper',\n",
       " 'join',\n",
       " 'ljust',\n",
       " 'lower',\n",
       " 'lstrip',\n",
       " 'maketrans',\n",
       " 'partition',\n",
       " 'replace',\n",
       " 'rfind',\n",
       " 'rindex',\n",
       " 'rjust',\n",
       " 'rpartition',\n",
       " 'rsplit',\n",
       " 'rstrip',\n",
       " 'split',\n",
       " 'splitlines',\n",
       " 'startswith',\n",
       " 'strip',\n",
       " 'swapcase',\n",
       " 'title',\n",
       " 'translate',\n",
       " 'upper',\n",
       " 'zfill']"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dir(\"Hello world!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Y_zjaNKMl_MM"
   },
   "source": [
    "### `len()`: 取得指定容器 (containers) 物件內含的元素個數"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ZS-f9F4apl69"
   },
   "source": [
    "所謂的容器物件，指的是部分物件可以包含其他物件的資料型態。目前我們所認識的只有字串 (`str`)，可以在一個物件包含多個單一字元。這種情況就可以呼叫 `len()` 函式來計算此物件內含的物件個數："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1148,
     "status": "ok",
     "timestamp": 1607419346573,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "GO_NYVwFlx4c",
    "outputId": "86351b81-5a78-484d-fa80-36af32086ee9"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12\n"
     ]
    }
   ],
   "source": [
    "print(len(\"Hello world!\"))  # 計算字串內含有多少個單一字元"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "o3JvueE6NjGA"
   },
   "source": [
    "## 物件型態轉換函式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "SHmuPVEKwJS0"
   },
   "source": [
    "數字物件與字串物件在特定的情況下，是可以互相轉換的。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JFF3dbEieiVL"
   },
   "source": [
    "### `int()`：轉換為整數"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "H-0-qmAmgCl8"
   },
   "source": [
    "#### 由字串轉換為整數"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 860,
     "status": "ok",
     "timestamp": 1606963327375,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "El84DRXuNk-s",
    "outputId": "b3ebb86c-4f03-4139-e047-69ea2a8609ba"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "source": [
    "s = \"10\"\n",
    "print(s)\n",
    "print(type(s))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 869,
     "status": "ok",
     "timestamp": 1606963341419,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "uzwQed5FedHK",
    "outputId": "ea28fcc0-d71a-4df2-ef4f-40742e8f4f27"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "<class 'int'>\n"
     ]
    }
   ],
   "source": [
    "i = int(s)\n",
    "print(i)\n",
    "print(type(i))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "KK5ck1wogLmC"
   },
   "source": [
    "#### 由浮點數轉換為整數"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 738,
     "status": "ok",
     "timestamp": 1606963680774,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "XSAOeOOSffX6",
    "outputId": "d1dc8fd9-58bf-4463-e2da-a5adbe793c7b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.14159\n",
      "<class 'float'>\n"
     ]
    }
   ],
   "source": [
    "f = 3.14159\n",
    "print(f)\n",
    "print(type(f))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 770,
     "status": "ok",
     "timestamp": 1606963683499,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "Qi3STILRf8am",
    "outputId": "25cc2cfc-df0e-4619-a6ff-073d8d313f38"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n",
      "<class 'int'>\n"
     ]
    }
   ],
   "source": [
    "i_f = int(f)\n",
    "print(i_f)\n",
    "print(type(i_f))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Omapv0DoevKv"
   },
   "source": [
    "### `str()`：轉換為字串"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "iCCcx6nggjLz"
   },
   "source": [
    "#### 由整數轉換為字串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 902,
     "status": "ok",
     "timestamp": 1606963412259,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "kabiSTOhe4b1",
    "outputId": "7775b285-297d-41e0-efc6-0e0df99baf78"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "<class 'int'>\n"
     ]
    }
   ],
   "source": [
    "i = 10\n",
    "print(i)\n",
    "print(type(i))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 814,
     "status": "ok",
     "timestamp": 1606963424403,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "YcWPBfTCe7fX",
    "outputId": "cd81e191-711c-4ee5-943a-db196e43c1be"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "source": [
    "s = str(i)\n",
    "print(s)\n",
    "print(type(s))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "NNJkWli5glVQ"
   },
   "source": [
    "#### 由浮點數轉換為字串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1369,
     "status": "ok",
     "timestamp": 1607421807413,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "9pB-3xKXzhOK",
    "outputId": "ae53b2ae-4ef8-4bb9-e73a-74c31d587cbf"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.14159\n",
      "<class 'float'>\n"
     ]
    }
   ],
   "source": [
    "f = 3.14159\n",
    "print(f)\n",
    "print(type(f))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1002,
     "status": "ok",
     "timestamp": 1607421824655,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "0Et29npjzk2x",
    "outputId": "d19940fd-7cea-4dba-f66b-15651943a73e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.14159\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "source": [
    "s = str(f)\n",
    "print(s)\n",
    "print(type(s))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "o-Y2_jpUe-h2"
   },
   "source": [
    "### `float()`：轉換為浮點數"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Ei1JJwJXg22N"
   },
   "source": [
    "#### 由整數轉換為浮點數"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 777,
     "status": "ok",
     "timestamp": 1606963911954,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "VcWzR9aFfHhO",
    "outputId": "f3247262-2f3c-4adf-cde6-753230cec5a8"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "<class 'int'>\n"
     ]
    }
   ],
   "source": [
    "i = 10\n",
    "print(i)\n",
    "print(type(i))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 744,
     "status": "ok",
     "timestamp": 1606963516559,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "PbbigO8SfNJh",
    "outputId": "a1ec6179-e772-4ab4-a840-62dae4772065"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10.0\n",
      "<class 'float'>\n"
     ]
    }
   ],
   "source": [
    "f_i = float(i)\n",
    "print(f_i)\n",
    "print(type(f_i))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "yfKNYbekg5kw"
   },
   "source": [
    "#### 由字串轉換為浮點數"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 784,
     "status": "ok",
     "timestamp": 1606963902461,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "hf5aOb3pgwkC",
    "outputId": "384a842f-1b46-4a77-8a73-85b29f1ef7dc"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "source": [
    "s = \"10\"\n",
    "print(s)\n",
    "print(type(s))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 728,
     "status": "ok",
     "timestamp": 1606963558748,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "-QiOK3L2fRYm",
    "outputId": "35a5ff3a-fa84-4200-eea0-59c8c0433b86"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10.0\n",
      "<class 'float'>\n"
     ]
    }
   ],
   "source": [
    "f_s = float(s)\n",
    "print(f_s)\n",
    "print(type(f_s))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "u-PrZ5avh_RL"
   },
   "source": [
    "### 隱式 (Inplicit) 地由整數轉換為浮點數"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3d6Vq0Zs0Tud"
   },
   "source": [
    "多個物件在經由運算子運算過後，會合併成同一個物件，一般來說，不相同的資料型態並不能經由運算子來進行運算。底下僅列出某種特定的例外情形：整數與浮點數運算後，將會隱式 (Inplicit) 地被轉換為浮點數："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 532,
     "status": "ok",
     "timestamp": 1606964326660,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "RmJANjAFiKR2",
    "outputId": "65c76980-3892-4a5f-d35e-ee79d1a52e1d"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "13.14159\n",
      "<class 'float'>\n"
     ]
    }
   ],
   "source": [
    "x = 10 + 3.14159\n",
    "print(x)\n",
    "print(type(x))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rTYke2IijFmo"
   },
   "source": [
    "為什麼被稱為隱式呢？因為這個表達式並沒有使用 `float()` 函式將整數型態轉換為整數，就直接將整數及浮點數相加。但結果是 Python 會自動將整數轉換為浮點數。\n",
    "\n",
    "> 備註：其實我們並不建議常常利用這種特性，畢竟這樣有時候會讓程式碼難以維護（可讀性下降）、或是因為轉換失敗而造成錯誤發生，應儘量避免這種狀況。提出這個特性僅是讓各位認識這個機制，且未來在程式出錯時，可以做為一個除錯的追蹤方向。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "authorship_tag": "ABX9TyMqGlqKAUNg/pfn0jLxckjv",
   "collapsed_sections": [],
   "name": "Python Basics - Chapter 3 - Methods and Functions.ipynb",
   "provenance": [],
   "toc_visible": true
  },
  "jupytext": {
   "formats": "ipynb,py:light"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  },
  "toc-autonumbering": true,
  "toc-showcode": false
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
